package entity.invoke;

import entity.pojo.Student;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

public class Invoke {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        do {
            System.out.println("input a entity:Student or Book");
            try {
                Class<?> clazz = Class.forName("entity.pojo." + sc.next());
                Method[] methods = clazz.getDeclaredMethods();
                Object object = clazz.newInstance();
                for (Method method : methods) {
                    if (method.getName().startsWith("set")) {
                        String parameterTypes = method.getParameterTypes()[0].toString();
                        System.out.println("method is:" + method.getName().substring(3));
                        System.out.println("type is"+parameterTypes+",input a value");
                        if (parameterTypes.indexOf("Integer") >= 0) {
                            method.invoke(object, Integer.parseInt(sc.next()));
                        } else if (parameterTypes.indexOf("Double") >= 0) {
                            method.invoke(object, Double.parseDouble(sc.next()));
                        } else if (parameterTypes.indexOf("Student") >= 0) {
                            System.out.println("input a name,then input a age");
                            method.invoke(object, new Student(sc.next(), sc.nextInt(),sc.next()));
                        } else {
                            method.invoke(object, sc.next());
                        }
                    }
                }
                try {
                    Method me = clazz.getMethod("toString");
                    System.out.println(me.invoke(object));
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                System.out.println("实例化异常");
            } catch (IllegalAccessException e) {
                System.out.println("修饰符不匹配");
            } catch (InvocationTargetException e) {
                System.out.println("反射方法抛出异常");
            }

            System.out.println("if continue (y/n)");
        } while ("y".equals(sc.next()));


    }
}
